package com.tg.app.activity.device.ui.cameraview;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;

import com.appbase.custom.constant.CommonConstants;
import com.appbase.custom.constant.DeviceStateConstants;
import com.demo.view.TimeRuleView;
import com.tange.base.toolkit.DateUtil;
import com.tange.base.toolkit.StringUtils;
import com.tange.base.toolkit.TGThreadPool;
import com.tg.app.R;
import com.tg.app.helper.DeviceHelper;
import com.tg.app.view.ACPlayBackView;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.data.http.entity.WheelData;
import com.tg.data.media.OnMediaPlayListener;
import com.tg.oss.OssMgr;

import java.util.Calendar;
import java.util.TimeZone;

public class SdCardPlayBackFragment extends PlayBackBaseFragment implements PlaybackViewListener, OnMediaPlayListener {
    private boolean supportStartFlag = true;
    private int endTime;
    private boolean isTimeRuleScrolling = false;

    @Override
    public int getPlayType() {
        return CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD;
    }

    @Override
    public void createTGPlayback() {

    }

    @Override
    public void setSdCardSize(int sdCardSize, boolean newData) {
        int oldSize = this.mSdCardSize;
        super.setSdCardSize(sdCardSize, newData);

        TGLog.d(TAG,"sdCardSize = " + sdCardSize + ", this.mSdCardSize = " + this.mSdCardSize + ",mRecordDay" + mRecordDay + ",newData = " + newData);
        if (this.mSdCardSize == 0 && playBackView != null) {
            TGLog.d(TAG,"this.mSdCardSize == 0 && playBackView != null");
            playBackView.setBuyCloudServiceShow();
            playBackView.setSdCardNone();
        }


        if (newData && oldSize == -999 && this.mSdCardSize > 0) {
            getRecordList(mRecordDay);
        }
    }

    @Override
    public void autoScrollFunc() {
        TGLog.d(TAG,"autoScrollFunc isTimeRuleScorlling == " + isTimeRuleScrolling);
        if (!isTimeRuleScrolling) {
            curTimeValue = nowTimeValue;
            nowTimeValue += 1;
            TGLog.d(TAG,"nowTimeValue " + nowTimeValue + " endTime " + endTime);
            if (nowTimeValue > endTime) {
                TGThreadPool.getMainHandler().removeCallbacksAndMessages(null);
                if (playBackView.getTimeRuleView() != null) {
                    playBackView.getTimeRuleView().setCurTimeFrom(TimeRuleView.TIME_SET_FROM_AUTO);
                }
                playBackView.scrollEventTime(nowTimeValue, false, false);
                TGThreadPool.getMainHandler().removeCallbacksAndMessages(null);
                if (onDateItemListener != null){
                    onDateItemListener.onPlayComplete();
                }
                return;
            }
            playBackView.scrollEventTime(nowTimeValue, false, false);
            playBackView.setCurrentTime(nowTimeValue, false);
            if (isContainsTime(nowTimeValue)) {
                mPlaybackRunnableHelper.postDelayedForAutoScrollRunnable(1000 / speed);
            } else if (!supportStartFlag) {
                if (playBackView.getTimeRuleView() != null) {
                    playBackView.getTimeRuleView().setCurTimeFrom(TimeRuleView.TIME_SET_FROM_AUTO);
                }
                int nextTime = getNextPartStartTime(nowTimeValue);
                playBackView.setCurrentTime(nextTime, false);
                mPlaybackRunnableHelper.postDelayedForAutoScrollRunnable(1000);
            }
        } else {
            mPlaybackRunnableHelper.removeAutoScrollRunnable();
        }
    }


    public int getNextPartStartTime(int pTime) {
        int time = -1;
        for (TimeRuleView.TimePart timePart : this.recordTimes) {
            if (pTime < timePart.startTime) {
                time = timePart.startTime;
                break;
            }
        }
        if (time > 0) {
            int fTime = DateUtil.getTimeFiveSec(time);
            if (DateUtil.getTimeFiveSec(pTime) == fTime) {
                time = fTime + 5;//对五取整时相同，则加5s
            }
            TGLog.d(TAG, "getNextPartStartTime  p:%s time:%s", DateUtil.formatTimeHHmmss(pTime), DateUtil.formatTimeHHmmss(time));
        }
        return time;
    }


    @Override
    public void timeRuleJumpNextFunc() {
        TGLog.d(TAG, "timeRuleJumpNextFunc");
        int time = playBackView.getTimeRuleView().getCurrentTime();
        if (mTGPlayback != null) {
            int nextTime = time + 5;
            if (mTGPlayback.isContainsTime(nextTime)) {
                if (!mTGPlayback.isContainsTime(nextTime)) {
                    playBackView.setCurrentTime(nextTime, false, TimeRuleView.TIME_SET_FROM_AUTO);
                    mPlaybackRunnableHelper.postDelayedForTimeRuleViewJumpNextRunnable(0);
                } else {
                    playBackView.setCurrentTime(nextTime, true, TimeRuleView.TIME_SET_FROM_AUTO);
                }

            } else {
                if (playBackView.getTimeRuleView() != null) {
                    playBackView.getTimeRuleView().setCurTimeFrom(TimeRuleView.TIME_SET_FROM_AUTO);
                }
                time = getNextPartStartTime(time);
                if (time == -1) {
                    TGThreadPool.getMainHandler().removeCallbacksAndMessages(null);

                } else {
                    playBackView.setCurrentTime(time + 1, true, TimeRuleView.TIME_SET_FROM_AUTO);
                }
            }
        }
    }

    public void rePlayCurrentTime() {
        if (recordTimes.size() > 0) {
            playBackView.setCurrentTime(nowTimeValue, true, TimeRuleView.TIME_SET_FROM_MANUL);
        } else {
            if (DeviceHelper.isOff(mDeviceItem)) {
                setPlaybackOff();
            } else {
                getRecordList(this.mRecordDay);
            }

        }
    }

    @Override
    public void setListener() {
        playBackView.setPlaybackViewListener(this);
        messageDateAdapter.setOnDateItemListener(position -> {
            if (getSdCardSize() <= 0) {
                mDeviceUIHelper.setIsScrolled(false);
                return;
            }
            if (mDeviceItem != null && mDeviceItem.is_open != DeviceStateConstants.DEVICE_OPEN) {
                return;
            }
            TGThreadPool.getMainHandler().removeCallbacksAndMessages(null);
            playBackView.scrollStop();
            isTimeRuleScrolling = true;
            mDeviceUIHelper.setIsScrolled(true);


            onPlaybackPause();

            if (onDateItemListener != null){
                WheelData wheelData = SdCardPlayBackFragment.this.wheelData.get(position);
                mRecordDay = DateUtil.getLastSomeDate(position, mTimeZone);
                onDateItemListener.onClick(position, wheelData);
            }
        });


        playBackView.setOnPlaybackListener(new ACPlayBackView.OnPlaybackListener() {
            @Override
            public boolean canScrolled() {
                return getSdCardSize() > 0;
            }

            @Override
            public void onBuyClick() {
//                Intent intent = new Intent(getContext(), CloudServiceActivity.class);
//                DeviceSettingsInfo info = new DeviceSettingsInfo();
//                info.deviceID = mDeviceItem.id;
//                intent.putExtra(DeviceSettingsActivity.EXT_DEVICE_INFO, info);
//                intent.putExtra(CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE, CloudServiceActivity.EXT_CLOUD_SERVICE_TYPE_STORAGEORCAR);
//                startActivityForResult(intent, Activity.RESULT_FIRST_USER);

                TGToast.showToast("该功能暂未开放");
            }

            @Override
            public void onTimeChangedClick(String time) {
            }

            @Override
            public void onDeviceOff() {

            }

            @Override
            public void onNoServe() {
                if (mErrorMessageListener != null) {
                    mErrorMessageListener.onNoServe();
                }
            }
        });

    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        boolean isScrolled = mDeviceUIHelper != null && mDeviceUIHelper.isScrolled();
        if (DeviceHelper.isDeviceForeignIccid(mDeviceItem)) {
            setVideoNone();
        } else if (isScrolled && mSdCardSize == 0) {
            playBackView.setBuyCloudServiceShow();
            playBackView.setSdCardNone();
        } else {
            TGLog.d(TAG,"mSdCardSize ==" + mSdCardSize + ", mIsAnimationsStart = " + mIsAnimationsStart + ", mRecordDay = " + mRecordDay);
            if (mSdCardSize == 0) {
                playBackView.setBuyCloudServiceShow();
                playBackView.setSdCardNone();
            } else {
                if (mIsAnimationsStart) {
                    getRecordList(mRecordDay);
                }
            }
        }
    }

    public void showPlaybackControl(boolean show) {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) playBackView.getLayoutParams();
        if (show) {
            if (eventList.size() > 0) {
                if (DeviceHelper.isCar(mDeviceItem)) {
                    playBackView.show();
                }
            }
            mRecyclerView.setVisibility(View.VISIBLE);
            centerLine.setVisibility(View.VISIBLE);
            layoutParams.addRule(RelativeLayout.BELOW, R.id.playback_center_line);
            playBackView.showIndicatorLayout();
        } else {
            playBackView.hide();
            mRecyclerView.setVisibility(View.GONE);
            layoutParams.removeRule(RelativeLayout.BELOW);
            playBackView.setTimePartList(recordTimes);
            centerLine.setVisibility(View.GONE);
            playBackView.setBuyCloudServiceHidden(true);
            playBackView.setTimeVisible(View.GONE);
        }
    }

    @Override
    public void getRecordList(String rDay) {
        if (!StringUtils.isEmpty(rDay)) {
            this.mRecordDay = rDay;
        }
        eventList.clear();
    }

    @Override
    public void playBackControl(boolean pause) {
        isPlaybackPause = pause;
        TGThreadPool.getMainHandler().removeCallbacksAndMessages(null);
        if (pause){
            mPlaybackRunnableHelper.removeAutoScrollRunnable();
            onPlaybackPause();
        }else{
            playBackView.setCurrentTime(nowTimeValue, true);
        }
    }

    @Override
    public void onPlaybackRecordListResp(boolean hasError) {
        TGThreadPool.executeOnUiThread(this::refreshUi);
    }

    public boolean isContainsTime(int time) {
        boolean has = false;
        if (recordTimes.size() == 0) return false;
        for (TimeRuleView.TimePart timePart : this.recordTimes) {
            if (timePart.startTime <= time && time <= timePart.endTime) {
                has = true;
                break;
            }
        }
        return has;
    }

    public void setPlaybackTime(int time) {
        if (recordTimes.size() > 0){
            endTime = recordTimes.get(0).endTime;
        }

    }

    private void refreshUi() {
        if (recordTimes.size() > 0) {
            endTime = recordTimes.get(0).endTime;
            TGLog.d(TAG,"endTime " + endTime);
            if (!TextUtils.isEmpty(mJumpEventTime)) {
                int startTime = DateUtil.getSecondDay(mJumpEventTime) - 5;
                playBackView.setCurrentTime(startTime, true);
                mJumpEventTime = "";
            } else {
                int start = recordTimes.size() > 0 ? recordTimes.get(0).startTime : 0;
                playBackView.setCurrentTime(start, true,TimeRuleView.TIME_SET_FROM_MANUL);
            }
        } else {
            playBackView.setCurrentTime(TimeRuleView.MAX_TIME_VALUE, false);
        }
    }


    @Override
    public void onPlaybackOssFailed(long time, int failCount) {
        ossFailed = true;
        if (failCount >= OssMgr.MAX_ERROR_COUNT){
            mLostFilePopupWindowHelper.show(getContext(), DeviceHelper.isCar(mDeviceItem) ? R.string.car_cloud_file_lost : R.string.cloud_file_lost);
        }

        mPlaybackRunnableHelper.postDelayedForTimeRuleViewJumpNextRunnable(0);
    }

    public static boolean isAfterDays(TimeZone timeZone, long pts, String recordDay) {
        Calendar cl = Calendar.getInstance();
        cl.setTimeInMillis(pts);
        cl.setTimeZone(timeZone);
        int playDays = cl.get(Calendar.DAY_OF_MONTH);
        int playMonth = cl.get(Calendar.MONTH);

        Calendar calendar = DateUtil.getCalendar(recordDay + " 00:00:00");
        int recordDays = calendar.get(Calendar.DAY_OF_MONTH);
        int recordMonth = calendar.get(Calendar.MONTH);
        TGLog.d(TAG, "isAfterDays " + playDays + ", " + playMonth + ", " + recordDays + ", " + recordMonth);
        return recordMonth < playMonth || playDays > recordDays;
    }

    @Override
    public void onPlaybackSDNextTimePart(long pts) {
        TGLog.d(TAG, "pts == " + pts + ", mRecordDay " + mRecordDay);
        supportStartFlag = true;

        if (isAfterDays(mTimeZone, pts, mRecordDay)) {
            TGLog.d(TAG, "isAfterDays ");
            return;
        }
        int time = DateUtil.getSecondDay(pts, mTimeZone);
        if (time >= endTime){
            TGLog.d(TAG, "time >= endTime ");
            return;
        }
        TGLog.d(TAG,"time = " + time + ", currentTime = " + nowTimeValue);
        TGLog.d(TAG,"onPlaybackSDNextTimePart time :" + DateUtil.formatTimeHHmmss(time) + " onPlaybackSDNextTimePart currentTime " + DateUtil.formatTimeHHmmss(nowTimeValue));

        long delays = 0;
        if (DateUtil.isBeforeDays(mTimeZone, pts, mRecordDay)) {
            delays = TimeRuleView.MAX_TIME_VALUE - time;
            time = 0;
        }
        TGLog.d(TAG,"onPlaybackSDNextTimePart time :" + DateUtil.formatTimeHHmmss(time) + " " + pts);
        TGLog.d(TAG, "time :" + DateUtil.formatTimeHHmmss(time) + " " + pts);

        final int newTimeValue = time;
        TGThreadPool.getMainHandler().postDelayed(() -> {
            curTimeValue = nowTimeValue;
            nowTimeValue = newTimeValue;
            TGLog.d(TAG,"1 nowTimeValue = " + nowTimeValue);
            mPlaybackRunnableHelper.removeAutoScrollRunnable();
            mPlaybackRunnableHelper.postDelayedForAutoScrollRunnable(1000 / speed);
        }, delays);
    }

    @Override
    public void receiveData(int type, byte[] data) {
        super.receiveData(type, data);
    }

    @Override
    public void onPlaybackPause() {
        TGThreadPool.getMainHandler().removeCallbacksAndMessages(null);
    }

    @Override
    public void onTimeScrolled(String time) {
        mPlaybackRunnableHelper.removeAutoScrollRunnable();
        if (getSdCardSize() <= 0 || DeviceHelper.isOff(mDeviceItem)) {
            return;
        }
        if (mDeviceItem != null && mDeviceItem.is_open != DeviceStateConstants.DEVICE_OPEN) {
            return;
        }

        isTimeRuleScrolling = true;
        if (recordTimes.size() > 0) {
            if (landscape) {
                playBackView.setTimeVisible(View.GONE);
            } else {
                playBackView.setTimeVisible(View.VISIBLE);
                playBackView.setRuleTime(time);
            }
        }
    }


    @Override
    public void stopLive() {

    }

    @Override
    public void onPlayTime(int time, boolean auto) {
        if (getSdCardSize() <= 0 || DeviceHelper.isOff(mDeviceItem)) {
            return;
        }
        curTimeValue = nowTimeValue;
        nowTimeValue = time;
        isTimeRuleScrolling = false;
        playBackView.setTimeVisible(View.GONE);

        TGLog.d(TAG," onScrollStateChanged onPlayTime :" + DateUtil.formatTimeHHmmss(time));
        if (recordTimes.size() > 0) {
            boolean isContains = isContainsTime(time);
            boolean isContains1 = isContainsTime(time + 5);
            TGLog.d(TAG," onScrollStateChanged isContainsTime(time) :" + isContains);
            TGLog.d(TAG," onScrollStateChanged isContainsTime(time) :" + isContains1);
            if (isContains || isContains1) {
                curTimeValue = nowTimeValue;
                nowTimeValue = time;

                String newTimeStr = DateUtil.formatTimeHHmmss(nowTimeValue);
                newTimeStr = String.format("%s %s", mRecordDay, newTimeStr);
                TGLog.d(TAG," onScrollStateChanged newTimeStr :" + newTimeStr);
                long playTime = DateUtil.get2MillisYMDHHMMSS(newTimeStr);
                TGLog.d(TAG," onScrollStateChanged playTime :" + playTime);
                if (onDateItemListener != null){
                    onDateItemListener.onPlayTime(playTime);
                }
                mPlaybackRunnableHelper.removeAutoScrollRunnable();
                mPlaybackRunnableHelper.postDelayedForAutoScrollRunnable(1000 / speed);
            } else {
                if (onDateItemListener != null){
                    onDateItemListener.onPlayTime(0);
                }
                TGThreadPool.getMainHandler().removeCallbacksAndMessages(null);
            }
        }

    }

    @Override
    public void onPlay(int position) {
        if (onDateItemListener != null){
            onDateItemListener.onPlay(position);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (DeviceHelper.isOff(mDeviceItem)) {
            setPlaybackOff();
            return;
        }
        if (DeviceHelper.is4GDevice(mDeviceItem)) {
            if (!DeviceHelper.is4GExpired(mDeviceItem, true)){
                resume();
            }
        }
    }


    @Override
    public void onMediaPlayFirstTimestamp(long pts) {

    }


    @Override
    public void onMediaPlayUpdated(long pts) {
    }

    @Override
    public void onMediaCloudPlayUpdated(final long pts) {
        supportStartFlag = true;
        if (pts < 1000000000) return;
        long ptsMs = pts * 1000;
        long wait = 0;
        int playTime = DateUtil.getSecondDay(ptsMs, mTimeZone);
        curTimeValue = nowTimeValue;
        if (DateUtil.isBeforeDays(mTimeZone, ptsMs, mRecordDay)) {
            wait = TimeRuleView.MAX_TIME_VALUE - playTime;
            nowTimeValue = 0;
        } else {
            nowTimeValue = playTime;
        }
        TGThreadPool.executeOnUiThread(() -> playBackView.setCurrentTime(nowTimeValue, false));

        mPlaybackRunnableHelper.removeAutoScrollRunnable();
        mPlaybackRunnableHelper.postDelayedForAutoScrollRunnable(1000 / speed + wait);
        TGLog.d(TAG,"onScrollStateChanged onMediaCloudPlayUpdated: " + pts + "  " + DateUtil.formatTimeHHmmss(nowTimeValue));
    }

}
